package com.bkhech.boot.configure.security.core.filter;

import cn.hutool.core.util.StrUtil;
import com.bkhech.boot.configure.common.dto.ResultResponse;
import com.bkhech.boot.configure.common.util.servlet.ServletUtils;
import com.bkhech.boot.configure.security.core.api.auth.LoginUserApi;
import com.bkhech.boot.configure.security.config.SecurityProperties;
import com.bkhech.boot.configure.security.core.LoginUser;
import com.bkhech.boot.configure.security.core.util.SecurityFrameworkUtils;
import com.bkhech.boot.configure.security.core.util.WebFrameworkUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * Token 过滤器，验证 token 的有效性
 * 验证通过后，获得 {@link LoginUser} 信息，并加入到 Spring Security 上下文
 *
 * @author guowm
 * @date 2023/1/11
 */
@RequiredArgsConstructor
public class TokenAuthenticationFilter extends OncePerRequestFilter {

    final SecurityProperties securityProperties;

    final LoginUserApi loginUserApi;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        final String token = SecurityFrameworkUtils.obtainAuthorization(request, securityProperties.getTokenHeader());
        // 存在 token
        if (StrUtil.isNotEmpty(token)) {
            try {
                // 1.1 基于 token 构建登录用户
                LoginUser loginUser = buildLoginUserByToken(token);
                // 1.2 模拟 Login 功能，方便日常开发调试
                if (Objects.isNull(loginUser)) {
                    loginUser = mockLoginUser(request, token);
                }

                // 2. 设置当前用户
                if (Objects.nonNull(loginUser)) {
                    SecurityFrameworkUtils.setLoginUser(loginUser, request);
                }
            } catch (Throwable ex) {
                final ResultResponse<Object> result = ResultResponse.failed();
                ServletUtils.writeJSON(response, result);
                return;
            }
        }

        // 继续过滤链
        filterChain.doFilter(request, response);
    }

    private LoginUser buildLoginUserByToken(String token) {
        return loginUserApi.getLoginUser(token);
    }

    private LoginUser mockLoginUser(HttpServletRequest request, String token) {
        if (!securityProperties.getMockEnable()) {
            return null;
        }
        // 必须以 mockSecret 开头
        if (!token.startsWith(securityProperties.getMockSecret())) {
            return null;
        }
        // 构建模拟用户
        Long userId = Long.valueOf(token.substring(securityProperties.getMockSecret().length()));
        return new LoginUser().setId(userId).setTenantId(WebFrameworkUtils.getTenantId(request));
    }
}
